import CommonDrawer from '@/components/CommonDrawer';
import useIntlCustom from '@/hooks/useIntlCustom';
// import { TSysMenuItem } from '@/types/TCommon';
import { DownOutlined } from '@ant-design/icons';
import { Button, Input, List, Tree, Typography } from 'antd';
import { FC, memo, useEffect, useMemo, useState } from 'react';
import { MenuRecord } from '../../menu/pageConfig';
import styles from './index.css';

const { Search } = Input;
const { Text } = Typography;

interface MenuAuthComType {
  open: boolean;
  onSubmit: (selectedPermissions: string[]) => void;
  onCancel: (val: boolean) => void;
  initialSelected?: string[]; // 初始选中的权限ID
}

interface TreeNode extends MenuRecord {
  title: string;
  key: string;
  children?: TreeNode[];
  checkable?: boolean;
  createTime?: string;
  updateTime?: string;
  parentMenuId?: string;
  menuId?: number;
}

// 写死的假数据
const mockTreeData: any[] = [
  // 工作台
  {
    id: 1,
    displayOrder: 1,
    identifierField: 'id',
    resourceName: '工作台',
    resourceUrl: '/workBench/overview',
    resourceDesc: '工作台',
    createTime: '2024-6-20 12:12:12',
    updateTime: '2024-6-21 13:13:13',
    createUser: 'testUser1',
    updateUser: 'testUser2',
    title: '工作台',
    key: '1',
    children: [
      {
        parentId: 1,
        id: 1000,
        displayOrder: 1,
        identifierField: 'id',
        resourceName: 'demo',
        resourceUrl: '/workBench/demo',
        resourceDesc: 'demo',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        title: 'demo',
        key: '1000',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
      {
        parentId: 1,
        id: 1001,
        displayOrder: 1,
        identifierField: 'id',
        resourceName: '管理员工作台',
        resourceUrl: '/workBench/overview',
        resourceDesc: '管理员工作台',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
      {
        parentId: 1,
        id: 1002,
        displayOrder: 2,
        identifierField: 'id',
        resourceName: '催收员工作台',
        resourceUrl: '/workBench/collectorBench',
        resourceDesc: '催收员工作台',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
    ],
  },
  // 案件管理
  {
    id: 2,
    displayOrder: 2,
    identifierField: 'id',
    resourceName: '案件管理',
    resourceUrl: '/caseManage/caseQuery',
    resourceDesc: '案件管理',
    createTime: '2024-6-20 12:12:12',
    updateTime: '2024-6-21 13:13:13',
    createUser: 'testUser1',
    updateUser: 'testUser2',
    children: [
      {
        parentId: 2,
        id: 2001,
        displayOrder: 1,
        identifierField: 'id',
        resourceName: '案件查询',
        resourceUrl: '/caseManage/caseQuery',
        resourceDesc: '案件查询',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
      {
        parentId: 2,
        id: 2002,
        displayOrder: 2,
        identifierField: 'id',
        resourceName: '案件列表',
        resourceUrl: '/caseManage/caseList',
        resourceDesc: '案件列表',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
      {
        parentId: 2,
        id: 2003,
        displayOrder: 3,
        identifierField: 'id',
        resourceName: '核心查询',
        resourceUrl: '/caseManage/cardQuery',
        resourceDesc: '核心查询',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
      {
        parentId: 2,
        id: 2004,
        displayOrder: 4,
        identifierField: 'id',
        resourceName: '案件审批',
        resourceUrl: '/systemManage/aduitManage',
        resourceDesc: '案件审批',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
    ],
  },
  // // 策略管理
  {
    id: 3,
    displayOrder: 3,
    identifierField: 'id',
    resourceName: '策略管理',
    resourceUrl: '/strategyManage/strategySetting',
    resourceDesc: '策略管理',
    createTime: '2024-6-20 12:12:12',
    updateTime: '2024-6-21 13:13:13',
    createUser: 'testUser1',
    updateUser: 'testUser2',
    children: [
      {
        parentId: 3,
        id: 3001,
        displayOrder: 1,
        identifierField: 'id',
        resourceName: '派案策略管理',
        resourceUrl: '/strategyManage/strategySetting',
        resourceDesc: '派案策略管理',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
      {
        parentId: 3,
        id: 3002,
        displayOrder: 3,
        identifierField: 'id',
        resourceName: '权重策略管理',
        resourceUrl: '/strategyManage/weightSetting',
        resourceDesc: '权重策略管理',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
      {
        parentId: 3,
        id: 3003,
        displayOrder: 2,
        identifierField: 'id',
        resourceName: '排序模板管理',
        resourceUrl: '/strategyManage/sortSetting',
        resourceDesc: '排序模板管理',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
      // {
      //   parentId: 3,
      //   id: 3004,
      //   displayOrder: 4,
      //   identifierField: 'id',
      //   resourceName: '工作台管理',
      //   resourceUrl: '/strategyManage/workbenck',
      //   resourceDesc: '工作台管理',
      //   createTime: '2024-6-20 12:12:12',
      //   updateTime: '2024-6-21 13:13:13',
      //   createUser: 'testUser1',
      //   updateUser: 'testUser2',
      //   permissions: [
      //     { permissionId: 'create', permissionName: '新增' },
      //     { permissionId: 'edit', permissionName: '编辑' },
      //     { permissionId: 'delete', permissionName: '删除' },
      //   ],
      // },
    ],
  },
  // 流程管理
  {
    id: 4,
    displayOrder: 4,
    identifierField: 'id',
    resourceName: '流程管理',
    resourceUrl: '/flowManage/nodeConfig',
    resourceDesc: '流程管理',
    createTime: '2024-6-20 12:12:12',
    updateTime: '2024-6-21 13:13:13',
    createUser: 'testUser1',
    updateUser: 'testUser2',
    children: [
      {
        parentId: 4,
        id: 4001,
        displayOrder: 1,
        identifierField: 'id',
        resourceName: '节点管理',
        resourceUrl: '/flowManage/nodeConfig',
        resourceDesc: '节点管理',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
      {
        parentId: 4,
        id: 4002,
        displayOrder: 2,
        identifierField: 'id',
        resourceName: '处理程序管理',
        resourceUrl: '/flowManage/program',
        resourceDesc: '处理程序管理',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
      {
        parentId: 4,
        id: 4003,
        displayOrder: 3,
        identifierField: 'id',
        resourceName: '标签管理',
        resourceUrl: '/flowManage/labelManage',
        resourceDesc: '标签管理',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
      {
        parentId: 4,
        id: 4004,
        displayOrder: 4,
        identifierField: 'id',
        resourceName: '规则管理',
        resourceUrl: '',
        resourceDesc: '规则管理',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        children: [
          {
            parentId: 4004,
            id: 400401,
            displayOrder: 1,
            identifierField: 'id',
            resourceName: '规则因子',
            resourceUrl: '/operationCenter/rules/ruleFactor',
            resourceDesc: '规则因子',
            createTime: '2024-6-20 12:12:12',
            updateTime: '2024-6-21 13:13:13',
            createUser: 'testUser1',
            updateUser: 'testUser2',
            permissions: [
              { permissionId: 'create', permissionName: '新增' },
              { permissionId: 'edit', permissionName: '编辑' },
              { permissionId: 'delete', permissionName: '删除' },
            ],
          },
          {
            parentId: 4004,
            id: 400402,
            displayOrder: 2,
            identifierField: 'id',
            resourceName: '规则管理',
            resourceUrl: '/operationCenter/rules/rulesConfig',
            resourceDesc: '规则管理',
            createTime: '2024-6-20 12:12:12',
            updateTime: '2024-6-21 13:13:13',
            createUser: 'testUser1',
            updateUser: 'testUser2',
            permissions: [
              { permissionId: 'create', permissionName: '新增' },
              { permissionId: 'edit', permissionName: '编辑' },
              { permissionId: 'delete', permissionName: '删除' },
            ],
          },
        ],
      },
    ],
  },
  // 运营管理
  {
    id: 5,
    displayOrder: 5,
    identifierField: 'id',
    resourceName: '运营管理',
    resourceUrl: '',
    resourceDesc: '运营管理',
    createTime: '2024-6-20 12:12:12',
    updateTime: '2024-6-21 13:13:13',
    createUser: 'testUser1',
    updateUser: 'testUser2',
    children: [
      {
        parentId: 5,
        id: 5001,
        displayOrder: 1,
        identifierField: 'id',
        resourceName: 'XXX监控',
        resourceUrl: '',
        resourceDesc: 'XXX监控',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
    ],
  },
  // 数据管理
  {
    id: 6,
    displayOrder: 6,
    identifierField: 'id',
    resourceName: '数据管理',
    resourceUrl: '/dataManage/realtime',
    resourceDesc: '数据管理',
    createTime: '2024-6-20 12:12:12',
    updateTime: '2024-6-21 13:13:13',
    createUser: 'testUser1',
    updateUser: 'testUser2',
    children: [
      {
        parentId: 6,
        id: 6001,
        displayOrder: 1,
        identifierField: 'id',
        resourceName: '实时数据流',
        resourceUrl: '/dataManage/realtime',
        resourceDesc: '实时数据流',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
      {
        parentId: 6,
        id: 6002,
        displayOrder: 2,
        identifierField: 'id',
        resourceName: '离线数据管理',
        resourceUrl: '/dataManage/offline',
        resourceDesc: '离线数据管理',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
      {
        parentId: 6,
        id: 6003,
        displayOrder: 3,
        identifierField: 'id',
        resourceName: '名单管理',
        resourceUrl: '/dataManage/callList',
        resourceDesc: '名单管理',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
      {
        parentId: 6,
        id: 6004,
        displayOrder: 4,
        identifierField: 'id',
        resourceName: '短信模版管理',
        resourceUrl: '/dataManage/smsTemplate',
        resourceDesc: '短信模版管理',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
    ],
  },
  // // 分析中心
  {
    id: 7,
    displayOrder: 7,
    identifierField: 'id',
    resourceName: '分析中心',
    resourceUrl: '',
    resourceDesc: '分析中心',
    createTime: '2024-6-20 12:12:12',
    updateTime: '2024-6-21 13:13:13',
    createUser: 'testUser1',
    updateUser: 'testUser2',
    children: [
      {
        parentId: 7,
        id: 7001,
        displayOrder: 1,
        identifierField: 'id',
        resourceName: '客户洞察',
        resourceUrl: '',
        resourceDesc: '客户洞察',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
    ],
  },
  // 系统管理
  {
    id: 8,
    displayOrder: 8,
    identifierField: 'id',
    resourceName: '系统管理',
    resourceUrl: '/systemManage/menu',
    resourceDesc: '系统管理',
    createTime: '2024-6-20 12:12:12',
    updateTime: '2024-6-21 13:13:13',
    createUser: 'testUser1',
    updateUser: 'testUser2',
    children: [
      {
        parentId: 8,
        id: 8001,
        displayOrder: 1,
        identifierField: 'id',
        resourceName: '菜单管理',
        resourceUrl: '/systemManage/menu',
        resourceDesc: '菜单管理',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
      {
        parentId: 8,
        id: 8002,
        displayOrder: 2,
        identifierField: 'id',
        resourceName: '数据字典',
        resourceUrl: '/systemManage/dict',
        resourceDesc: '数据字典',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
      {
        parentId: 8,
        id: 8003,
        displayOrder: 3,
        identifierField: 'id',
        resourceName: '机构管理',
        resourceUrl: '/systemManage/org',
        resourceDesc: '机构管理',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
      {
        parentId: 8,
        id: 8004,
        displayOrder: 4,
        identifierField: 'id',
        resourceName: '岗位管理',
        resourceUrl: '/systemManage/position',
        resourceDesc: '岗位管理',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
      {
        parentId: 8,
        id: 8005,
        displayOrder: 5,
        identifierField: 'id',
        resourceName: '角色管理',
        resourceUrl: '/systemManage/role',
        resourceDesc: '角色管理',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
      {
        parentId: 8,
        id: 8006,
        displayOrder: 6,
        identifierField: 'id',
        resourceName: '用户管理',
        resourceUrl: '/systemManage/user',
        resourceDesc: '用户管理',
        createTime: '2024-6-20 12:12:12',
        updateTime: '2024-6-21 13:13:13',
        createUser: 'testUser1',
        updateUser: 'testUser2',
        permissions: [
          { permissionId: 'create', permissionName: '新增' },
          { permissionId: 'edit', permissionName: '编辑' },
          { permissionId: 'delete', permissionName: '删除' },
        ],
      },
    ],
  },
];

// 数据转换函数：为每个节点添加 title 和 key
const transformTreeData = (data: any[]): TreeNode[] => {
  return data.map((item) => ({
    ...item,
    title: item.resourceName || item.name || `菜单${item.id}`,
    key: String(item.id),
    children: item.children ? transformTreeData(item.children) : undefined,
    parentMenuId: item.parentId ? String(item.parentId) : undefined,
    menuId: item.id,
  }));
};

const MenuAuthCom: FC<MenuAuthComType> = ({ open, onSubmit, onCancel, initialSelected = [] }) => {
  const { translate } = useIntlCustom();
  const t = (key: string, params?: Record<string, any>) => translate('systemManage', key, params);
  const [treeData, setTreeData] = useState<TreeNode[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<string[]>(initialSelected);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [searchValue, setSearchValue] = useState('');

  // 初始化数据
  useEffect(() => {
    if (open) {
      // 转换数据格式
      const transformedData = transformTreeData(mockTreeData);
      setTreeData(transformedData);
      // 默认展开第一级
      const firstLevelKeys = transformedData.map((item) => item.key);
      setExpandedKeys(firstLevelKeys);
    }
  }, [open]);

  // 搜索过滤
  const filteredTreeData = useMemo(() => {
    if (!searchValue) return treeData;

    const filterTree = (nodes: TreeNode[]): TreeNode[] => {
      return nodes
        .filter((node) => {
          const titleMatch = node.title.toLowerCase().includes(searchValue.toLowerCase());
          const childrenMatch = node.children && filterTree(node.children).length > 0;
          return titleMatch || childrenMatch;
        })
        .map((node) => ({
          ...node,
          children: node.children ? filterTree(node.children) : undefined,
        }));
    };

    return filterTree(treeData);
  }, [treeData, searchValue]);

  // 获取所有权限节点（扁平化）
  const getAllPermissionNodes = (nodes: TreeNode[]): TreeNode[] => {
    const result: TreeNode[] = [];
    const traverse = (nodeList: TreeNode[]) => {
      nodeList.forEach((node) => {
        result.push(node);
        if (node.children) {
          traverse(node.children);
        }
      });
    };
    traverse(nodes);
    return result;
  };

  // 获取选中节点的完整路径
  const getSelectedPaths = (): string[] => {
    const allNodes = getAllPermissionNodes(treeData);
    const selectedNodes = allNodes.filter((node) => selectedKeys.includes(String(node.key)));

    const getNodePath = (node: TreeNode): string => {
      const path: string[] = [node.title];
      let current = node;

      while (current.parentMenuId && current.parentMenuId !== '0') {
        const parent = allNodes.find((n) => n.menuId?.toString() === current.parentMenuId);
        if (parent) {
          path.unshift(parent.title);
          current = parent;
        } else {
          break;
        }
      }

      return path.join('/');
    };

    return selectedNodes.map(getNodePath);
  };

  // 全选
  const handleSelectAll = () => {
    const allNodes = getAllPermissionNodes(treeData);
    const allKeys = allNodes.map((node) => String(node.key));
    setSelectedKeys(allKeys);
  };

  // 清空
  const handleClear = () => {
    setSelectedKeys([]);
  };

  // 树节点选择变化
  const handleTreeSelect = (checkedKeys: any, info: any) => {
    // Tree组件的onCheck回调返回的是数组格式，确保所有key都是字符串
    const stringKeys = Array.isArray(checkedKeys) ? checkedKeys.map(String) : [];
    setSelectedKeys(stringKeys);
  };

  // 树节点展开变化
  const handleTreeExpand = (expandedKeys: any[]) => {
    setExpandedKeys(expandedKeys.map(String));
  };

  // 提交
  const handleSubmit = () => {
    onSubmit(selectedKeys);
    onCancel(false);
  };

  // 关闭
  const handleClose = () => {
    onCancel(false);
  };

  // 更新初始选中值 - 只在组件打开时设置初始值
  // useEffect(() => {
  //   if (open) {
  //     setSelectedKeys(initialSelected);
  //   }
  // }, [open, initialSelected]);

  const selectedPaths = getSelectedPaths();
  return (
    <CommonDrawer
      visible={open}
      title={t('permissionConfig')}
      onClose={handleClose}
      width={800}
      showDefaultFooter
      onCancel={handleClose}
      onConfirm={handleSubmit}
      confirmText={t('confirm')}
      cancelText={t('cancel')}
    >
      <div className={styles.drawerBody}>
        {/* 左侧权限树 */}
        <div className={styles.leftPane}>
          <div className={styles.searchBar}>
            <Search
              value={searchValue}
              onChange={(e) => setSearchValue(e.target.value)}
              className={styles.searchInput}
            />
            <div className={styles.between}>
              <Text type="secondary">{t('totalItems', { count: getAllPermissionNodes(treeData).length })}</Text>
              <Button type="link" size="small" onClick={handleSelectAll}>
                {t('selectAll')}
              </Button>
            </div>
          </div>

          <Tree
            checkable
            checkedKeys={selectedKeys}
            expandedKeys={expandedKeys}
            onCheck={handleTreeSelect}
            onExpand={handleTreeExpand}
            treeData={filteredTreeData}
            showLine
            showIcon={false}
            switcherIcon={<DownOutlined />}
            className={styles.tree}
          />
        </div>

        {/* 右侧已选权限 */}
        <div className={styles.rightPane}>
          <div className={styles.searchBar}>
            <div className={styles.between}>
              <Text type="secondary">{t('selectItems', { count: selectedKeys.length })}</Text>
              <Button type="link" size="small" onClick={handleClear}>
                {t('clear')}
              </Button>
            </div>
          </div>

          <List
            size="small"
            dataSource={selectedPaths}
            renderItem={(item) => (
              <List.Item className={styles.listItem}>
                <Text>{item}</Text>
              </List.Item>
            )}
            className={styles.list}
          />
        </div>
      </div>
    </CommonDrawer>
  );
};

export default memo(MenuAuthCom);
